package com.jctrip.hotel.route.aspect;

import java.lang.reflect.Method;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.jctrip.hotel.common.annotation.RedisLimitAnnotation;
import com.jctrip.hotel.common.constant.RedisKeyConstant;
import com.jctrip.hotel.domain.dao.HtRequestLimitDao;
import com.jctrip.hotel.domain.entity.HtRequestLimit;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author henry
 * @Date 2023/11/24 11:36
 * @Description
 */

@Aspect
@Component
@Slf4j
public class RequestLimitAspect {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private DefaultRedisScript<Long> redisluaScript;
    @Resource
    private HtRequestLimitDao htRequestLimitDao;

    @Pointcut(value = "@annotation(com.jctrip.hotel.common.annotation.RedisLimitAnnotation)")
    public void rateLimit() {
    }

    @Before("rateLimit()")
    public void limiter(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RedisLimitAnnotation annotation = method.getAnnotation(RedisLimitAnnotation.class);
        if (Objects.isNull(annotation)) {
            return;
        }
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String routeId = request.getHeader("routeId");
        if (StringUtils.isBlank(routeId)) {
            throw new RuntimeException("routeId不能为空");
        }
        String key = annotation.key();
        HtRequestLimit limit = htRequestLimitDao.selectOne(
                new LambdaQueryWrapper<HtRequestLimit>().eq(HtRequestLimit::getRouteId, routeId)
                        .eq(HtRequestLimit::getMethodName, key));
        if (Objects.isNull(limit)) {
            return;
        }
        key = String.format(RedisKeyConstant.HOTEL_MAIN_REQUEST_LIMIT, key, routeId);
        Long acquired =
                stringRedisTemplate.execute(redisluaScript, Lists.newArrayList(key), limit.getRateLimit().toString(),
                        limit.getExpire().toString());
        if (acquired == 0) {
            throw new RuntimeException("访问频率过快,请稍后重试");
        }
    }
}
